<script lang="ts" setup>
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { detailApi, createApi, editApi, getCategoryTreesApi } from '#/api/system/help';

const formData = ref();

const [Form, formApi] = useVbenForm({
  schema: [
    {
      fieldName: 'id',
      label: 'ID',
      defaultValue: 0,
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: [''],
      },
    },
    {
      fieldName: 'category_id',
      label: '分类',
      component: 'ApiTreeSelect',
      componentProps: {
        // 菜单接口
        api: getCategoryTreesApi,
        // 菜单接口转options格式
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        class: 'w-[100%]',
        placeholder: '请选择分类',
        allowClear: true
      },
      rules: 'required',
    },
    {
        fieldName: 'title',
        label: '标题',
        component: 'Input',
        componentProps: {
            placeholder: '请输入标题',
        },
        rules: 'required',
    }, 
    {
        fieldName: 'content',
        label: '内容',
        component: 'Editor',
        defaultValue: '',
    },
    {
        fieldName: 'sort',
        label: '排序',
        defaultValue: 10000,
        component: 'InputNumber',
        rules: 'required',
    },
    {
        fieldName: 'status',
        label: '状态',
        defaultValue: 1,
        component: 'Switch',
        componentProps: {
            class: 'w-auto',
            checkedChildren: '启用',
            checkedValue: 1,
            unCheckedChildren: '停用',
            unCheckedValue: 0,
        },
    },
  ],
  showDefaultActions: false,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    drawerApi.lock();
    (values.id ? editApi(values) : createApi(values))
      .then((res) => {
        message.success({
          content: res.message,
        });
        drawerApi.close();
      })
      .catch(() => {
        drawerApi.unlock();
      });
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData();
      formApi.resetForm();
      formData.value = data;
      if (data.id) {
        detailApi(data.id).then((res) => {
          formApi.setValues(res);
        })
      }
    }
  },
  overlayBlur: 1,
  class: 'w-[550px]',
});

const getDrawerTitle = computed(() => {
  return formData.value?.id
    ? '编辑文档'
    : '新增文档';
});


</script>
<template>
  <Drawer :title="getDrawerTitle">
    <Form />
  </Drawer>
</template>
